package org.zjvis.graph.analysis.service.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.UUID;

/**
 * @date 2020/04/10
 */
@Component
@Aspect
public class LogAspect {

    private final static Logger logger = LoggerFactory.getLogger("LogAspect");

    public static final String TRACE_ID = "traceId";

    @Pointcut("execution(* org.zjvis..service..*.*(..))) " +
        "and execution(* org.zjvis..util*..*.*(..)))")
    public void serviceAspect() {
    }

    @Pointcut("execution(* org.zjvis.graph.analysis..service..*.*(.., org.zjvis.graph.analysis.service.dto.GraphDTO, ..)) || " +
            " execution(* org.zjvis.graph.analysis.service.interceptor.MybatisInterceptor.*(..))")
    public void excludeAspect() {
    }

    @Pointcut("serviceAspect()")
    public void aroundAspect() {
    }

    @Around("aroundAspect()")
    public Object around(JoinPoint joinPoint) throws Throwable {
        if (StringUtils.isEmpty(MDC.get(TRACE_ID))) {
            MDC.put(TRACE_ID, UUID.randomUUID().toString());
        }
        if (joinPoint.getSignature().toString().equals(
            "List org.zjvis.datascience.service.mapper.DatasetMapper.getAllTableDataSourceNeedScheduled()")) {
            return ((ProceedingJoinPoint) joinPoint).proceed();
        }
        logger.info(String
            .format("uri:%s, ==>begin", joinPoint.getSignature()));
        long start = System.currentTimeMillis();
        Object result = ((ProceedingJoinPoint) joinPoint).proceed();
        long end = System.currentTimeMillis();
        logger.info(String.format("uri:%s,proc_time:%s,<==end", joinPoint.getSignature().toString(),
            end - start));
        return result;
    }
}
